package com.momoc.mrpc.rpc.serialize;

import com.momoc.mrpc.config.MRpcConfig;
import com.momoc.mrpc.util.SpringContextUtil;
import java.util.Map;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * @author momoc
 * @version 1.0
 * @className SerializeManager
 * @description
 * @date 2022/7/25 3:24 下午
 */
@Component
public class SerializeManager implements ApplicationContextAware {

    ApplicationContext applicationContext;

    @Autowired
    MRpcConfig mRpcConfig;
    public static MRpcSerializeMode mRpcSerializeMode;

    public static Map<String, MRpcSerializeMode> beansOfType;

    @PostConstruct
    public void postConstruct(){
        beansOfType = applicationContext.getBeansOfType(MRpcSerializeMode.class);
        if (mRpcConfig.getMrpcSerializeMode() == null){
            mRpcSerializeMode = SpringContextUtil.getBean(DefaultMRpcSerializeMode.class);
            return;
        }
        //通过code获取序列化算法
        for (MRpcSerializeMode value : beansOfType.values()) {
            if (mRpcConfig.getMrpcSerializeMode().equals(value.getSerializeTypeString())) {
                mRpcSerializeMode = value;
            }
        }
        if (mRpcSerializeMode == null){
            throw new RuntimeException("mRPC error 未设置序列化方式");
        }
    }


    public static MRpcSerializeMode getMRpcSerializeMode(){
        return mRpcSerializeMode;
    }


    public static MRpcSerializeMode getMRpcSerializeMode(byte type){
        for (MRpcSerializeMode value : beansOfType.values()) {
            if (type==value.getSerializeTypeByte()) {
                return value;
            }
        }
        return mRpcSerializeMode;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
